import Request from 'utils/request';
import SystemUtil from 'utils/systemUtil';

import Location from 'models/map/location';

export default class CommonApi {
  static authLogin(code) {
    const apiName = 'wechat/getCodeFromWechatAuth';

    return Request.post(apiName, {
      code: code
    }).then(res => {
      let data = res.data;
      let weChatUserInfo = data.sessionInfo.weChatUserInfo;
      return {
        authToken: data.auth_token,
        refreshToken: data.refresh_token,
        user: weChatUserInfo
      };
    });
  }

  static getTocken(refreshToken) {
    let apiName;
    if (process.env.isMiniprogram) {
      apiName = 'api/wechatMiniProgram/wechatForRefreshToken';
    } else {
      apiName = 'wechat/wechatForRefreshToken';
    }

    return Request.post(apiName, {
      refreshToken: refreshToken
    }).then(res => {
      let data = res.data;
      let weChatUserInfo = data.sessionInfo.weChatUserInfo;
      return {
        authToken: data.auth_token_wechat,
        refreshToken: data.refresh_token_wechat,
        user: weChatUserInfo
      };
    });
  }

  static getWxConfig(url) {
    const apiName = 'wechat/getConfig';
    return Request.post(apiName, {
      url: url
    }).then(res => {
      return res.data;
    });
  }

  static getLocationData(openid, lnglat, isDefault = false) {
    const apiName = 'wechat/saveUserLocation';
    return Request.post(apiName, {
      openid: openid,
      longitude: lnglat.longitude,
      latitude: lnglat.latitude
    }).then(res => {
      let location = new Location(res.data, isDefault);
      return location;
    })
  }

  static getShopInfo(obj) {
    const apiName = 'api/wehcatshop/shopInfo';

    let postData = {};

    let partnerId = obj.partnerId;
    if (SystemUtil.isEmpty(partnerId)) {
      postData.branchId = obj.branchId;
    } else {
      postData.partnerId = partnerId;
    }

    return Request.post(apiName, postData).then(res => {
      let data = res.data;
      return data;
    });
  }
}
